<template>
  <div class="create-component-list">
    <div
      class="component-item"
      v-for="item in list"
      :key="item.id"
      @click="onItemClick(item)"
    >
      <l-text v-bind="item.props"></l-text>
    </div>
    <pos-uploader
      action="https://api.superbed.cn/upload" drag :autoUpload="true"
      ref="uploader" listType="picture" :onUploaded="handleUploaded"
    />
  </div>
</template>

<script setup lang="ts">
import type { IComponentData } from '@/stores/editor';
import { v4 as uuidv4 } from 'uuid'
import LText from './LText.vue';
import PosUploader from './PosUploader.vue';
import { imageDefaultProps } from '@/defaultProps';
import { message } from 'ant-design-vue';
import { getImageDimensions } from '@/helper';
const emits = defineEmits(['on-item-click'])
const props = defineProps({
  list: {
    type: Array<{[key: string]: any}>,
    required: true
  }
})

const onItemClick = (data:any) => {
  emits('on-item-click', data)
}

const handleUploaded = (fileSrc: string) => {
  const data:IComponentData = {
    id: uuidv4(),
    name: 'l-image',
    props: {
      ...imageDefaultProps,
      src: fileSrc
    }
  }
  getImageDimensions(fileSrc).then(({naturalWidth}) => {
    const maxWidth = 373
    data.props.width = naturalWidth > maxWidth ? maxWidth : naturalWidth
    message.success('上传成功！')
    onItemClick(data)
  })
}
</script>